package com.tools.common.serialize;

import com.tools.common.application.BaseApp;
import com.tools.common.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FileRepo implements IRepo {
    private static FileRepo sRepo = null;

    public static FileRepo instance() {
        if(sRepo == null) {
            synchronized (FileRepo.class) {
                if(sRepo == null) {
                    sRepo = new FileRepo();
                }
            }
        }

        return sRepo;
    }

    private FileRepo() {
    }

    private File getRepoFile(String key) {
        File dir = FileUtils.getRepoDir(BaseApp.appContext());
        if(dir == null) {
            return null;
        }

        return new File(dir + File.separator + key);
    }

    @Override
    public <T> void store(String key, T obj) {
        File f = getRepoFile(key);
        if(f == null) {
            return;
        }

        ObjectOutputStream os = null;
        try {
            os = new ObjectOutputStream(new FileOutputStream(f));
            os.writeObject(obj);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public <T> T load(String key, Class clazz) {
        File f = getRepoFile(key);
        if(f == null) {
            return null;
        }

        ObjectInputStream is = null;
        T target = null;
        try {
            is = new ObjectInputStream(new FileInputStream(f));
            target = (T) is.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return target;
    }
}
